package com.businesscard.system.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Web安全配置类
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // 添加这个bean定义
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()  // 禁用CSRF，因为我们使用前后端分离
            .authorizeRequests()
                .antMatchers("/static/**", "/css/**", "/js/**", "/images/**").permitAll()
                .antMatchers("/user/login", "/user/register", "/user/captcha", "/user/forget-password").permitAll()
                .antMatchers("/admin/login", "/admin/captcha").permitAll()
                .anyRequest().permitAll()  // 允许所有请求，实际权限由自定义拦截器控制
            .and()
            .formLogin().disable()  // 禁用表单登录，使用自定义登录
            .logout()
                .logoutUrl("/user/logout")
                .logoutSuccessUrl("/user/login")
                .permitAll()
            .and()
            .sessionManagement()
                .invalidSessionUrl("/user/login")
                .maximumSessions(1)
                .expiredUrl("/user/login");
    }
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 静态资源不走过滤器链
        web.ignoring()
           .antMatchers("/static/**", "/css/**", "/js/**", "/images/**", "/**/*.css", "/**/*.js");
    }
}
